#include <SdFat.h>         // SdFat Libraries
#include <SdFatUtil.h>     // SdFat Libraries
#include <ctype.h>         // SdFat Libraries

#define actLED 2 //Activity LED Port

#define CS      8   //microSD shield port
#define MOSI    11  //microSD shield port
#define MISO    12  //microSD shield port
#define SCK     13  //microSD shield port

//Create the variables to be used by SdFat Library
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;
char name[] = "GPS_log.txt";    //Create an array that contains the name of our file.
char in_char=0;
int index=0;                    //Index will keep track of our position within the contents buffer.


void setup(){
    
    pinMode(0, INPUT);     //Serial RX
    pinMode(1, OUTPUT);    //Serial TX
    
    pinMode(10, OUTPUT);   //microSD pin
    pinMode(CS, OUTPUT);   //microSD pin
    pinMode(MOSI, OUTPUT); //microSD pin
    pinMode(MISO, INPUT);  //microSD pin
    pinMode(SCK, OUTPUT);  //microSD pin
    pinMode(10, OUTPUT);   //microSD pin
    
    pinMode(actLED,OUTPUT); //Activity LED pin
    
    card.init();               //Initialize the SD card and configure the I/O pins.
    volume.init(card);         //Initialize a volume on the SD card.
    root.openRoot(volume);     //Open the root directory in the volume.
    
    Serial.begin(9600);        //Serial
    Serial1.begin(9600);       
}

void loop(){
  file.open(root, name, O_CREAT | O_APPEND | O_WRITE);    //Open or create the file 'name' in 'root' for writing to the end of the file.
  while (Serial1.available()){
    digitalWrite(actLED,HIGH);  //Start Activity
    in_char=char(Serial1.read());
    file.print(in_char);    //Write the 'contents' array to the end of the file.
    Serial.print(in_char);
    digitalWrite(actLED,LOW);   //End Activity
  }
  file.close();    //Close the file
}

